<?php
namespace App\Http\Middleware\Auth\Refresh\Trade;

use Closure;
use App\Core\Entity\Session\UserEntity;
use App\Models\Trade\Demand\DemandRefreshModel;
use App\Exceptions\Response\Middleware\MiddlewareException;
use App\Exceptions\Response\Middleware\MiddlewareCode;

/**
 * 数据刷新检查
 */
class Demand
{

    /**
     * 用户实体
     *
     * @var \App\Core\Entity\Session\UserEntity
     */
    protected $user;

    /**
     * 初始化用户实体
     *
     * @param UserEntity $user            
     */
    public function __construct(UserEntity $user)
    {
        $this->user = $user;
    }

    /**
     * 前置 | 后置
     *
     * @param \Illuminate\Http\Request $request            
     * @param \Closure $next            
     * @return \Closure $next
     */
    public function handle($request, Closure $next)
    {
        $id = $request->input('id');
        $userId = $this->user->getUserId();
        
        // 刷新次数检查
        if ($id && ($item = DemandRefreshModel::findItemByToday($userId, $id)->shift())) {
            if ($item['amount'] >= config('custom.auth.refresh.demand')) {
                throw new MiddlewareException(MiddlewareCode::MIDDLEWARE_AUTH_REFRESH_LIMIT);
            }
        }

        return $next($request);
    }
}